let tree = [
  {
    id: 1,
    name: "1",
    pid: 0,
    children: [
      {
        id: 2,
        name: "2",
        pid: 1,
        children: [],
      },
      {
        id: 3,
        name: "3",
        pid: 1,
        children: [
          {
            id: 4,
            name: "4",
            pid: 3,
            children: [],
          },
        ],
      },
    ],
  },
];

function dealTree(tree) {
  let res = [];
  for (let item of tree) {
    const { children, ...obj } = item;
    if (children && children.length) {
      res = res.concat(dealTree(children));
    }
    res.push(obj);
  }
  return res.sort((x, y) => x.id - y.id);
}

// console.log(dealTree(tree));

function dealTree2(tree) {
  return tree.reduce((res, item) => {
    const { children, ...obj } = item;
    return res.concat(
      obj,
      children && children.length ? dealTree2(children) : []
    );
  }, []);
}

console.log(dealTree2(tree));
